<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="view-table">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow"> </XForm>
      </template>
      <template #toolbar_btns>
        <!-- <VButton auth="/pmc/base/asinConfig/notAsin" type="primary" @click="notAsinQuery"> 未绑定ASIN </VButton> -->

        <VButton auth="/pmc/plan/operateForecast/import" icon="Download" @click="onImport"> 导入 </VButton>
        <VButton auth="/pmc/plan/operateForecast/export" @click="onExport"> <svg-icon icon-class="import" /> 导出 </VButton>
        <VButton auth="/pmc/plan/operateForecast/showDaySales" type="primary" @click="showDaySales"> 显示去年销量 </VButton>

        <!-- <VButton icon="Download" type="" @click="onImport">导入</VButton>
        <el-button>
          <span class="flex items-center" @click="onExport"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
        </el-button>

        <el-button type="primary" @click="showDaySales">显示去年销量</el-button> -->

        <el-dropdown trigger="click" @command="batchOptionsEvent">
          <el-button type="primary">
            批量操作
            <div class="dk-iconfont icon-ArrowDown"></div>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu v-matomo>
              <template v-for="item in batchOptions" :key="item.label">
                <el-dropdown-item :command="item.value">{{ item.label }}</el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- <el-button type="danger" @click="onDeleteManually">批量删除</el-button> -->
        <VButton auth="/pmc/plan/operateForecast/batchDelete" type="danger" @click="onDeleteManually"> 批量删除 </VButton>

        <div class="ml-auto">
          历史分析数据:
          <el-date-picker v-model="archived_at" style="width: 150px" type="date" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
        </div>
      </template>

      <template #monthColumn="{ row, column }">
        <div class="grid grid-cols-2 gap-y-2">
          <div v-if="row[column.title]">
            日常
            <el-input
              v-model="row[column.title].daily_sales"
              placeholder="销量"
              style="width: 60px"
              @blur="salesChange({ ...row[column.title], id: row.id, asin: row.asin })"
              :disabled="row[column.title].disabled"
            />
          </div>

          <div v-if="row[column.title]">
            活动
            <el-input
              v-model="row[column.title].activity_sales"
              placeholder="销量"
              style="width: 60px"
              @blur="salesChange({ ...row[column.title], id: row.id, asin: row.asin })"
              :disabled="row[column.title].disabled"
            />
          </div>

          <VText title="总销量" :value="row?.[column.title]?.total_sales" :line="1" />
          <VText title="实际销量" :value="row?.[column.title]?.actual_sales" :line="1" />
        </div>

        <el-progress :percentage="row?.[column.title]?.scale" />
        <div v-if="row?.[column.title]?.day_month">（{{ row?.[column.title]?.day_month }}：实际销量 {{ row?.[column.title]?.day_total_sales }}）</div>
      </template>
    </VTable>

    <!-- ASIN销量趋势 -->
    <AsinSalesTrend ref="AsinSalesTrendRef" />

    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit">
      <!-- 批量修改预测销量 -->
      <template #SalesForecasts="{ form }">
        <el-input
          v-model="form.sales_forecasts"
          :autosize="{ minRows: 4, maxRows: 6 }"
          @keydown.tab="handleTab($event, form.sales_forecasts)"
          type="textarea"
          :placeholder="`国家 Asin sku 操作运营 X月日常 X月日常
            // 示例：
            // US B0CSDBB4N2 7395682 KoalaLuo 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
            // UK B0DPQ5KTJ6 9838734 KathyZhong 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0`"
        />
      </template>
    </ConfirmInput>

    <XLog ref="logRef" :api="salesForecastLog"></XLog>

    <!-- 导入 -->
    <DialogImport v-model:modelValue="visibleImport" :download-url="downloadUrl" :downloadApi="salesForecastDownloadImportYpl" downloadName="销量预测导入模板" :api="forecastimport" />

    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef" :callbackFn="callbackFn" />
  </VPage>
</template>

<script setup lang="jsx">
import {
  salesForecastList,
  salesForecastListByDate,
  salesForecastLog,
  salesForecastBatchUpdateSales,
  forecastimport,
  salesForecastCreateExportRecord,
  salesForecastDownloadImportYpl,
  batchUpdateActivityAndTransportType,
  deleteManually,
} from "@/api/plan"
import { getShopOptions } from "@/api/index.js"
import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"
const archived_at = ref("")
const handleTab = (event, text) => {
  event.preventDefault()

  const start = event.target.selectionStart
  const end = event.target.selectionEnd
  const spaces = " " // 可以根据需求设置空格数
  const before = text.substring(0, start)
  const after = text.substring(end)
  text = before + spaces + after
  currentConfirm.value.form.sales_forecasts = text
  // 更新光标位置
  setTimeout(() => {
    event.target.selectionStart = start + spaces.length
    event.target.selectionEnd = start + spaces.length
  }, 1)

  // 在这里处理Tab键按下的逻辑
}

import XForm from "@/components/XForm/index.vue"
// 弹窗 表单编辑
import ConfirmInput from "@/components/ConfirmInput/index.vue"
// 日志
import XLog from "@/components/XLog"
const logRef = ref()
// ASIN销量趋势
import AsinSalesTrend from "@/views/plan/components/AsinSalesTrend/index.vue"
const AsinSalesTrendRef = ref()

// 导入
import DialogImport from "@/components/DialogImport/index.vue"
const dialogImportRef = ref()
const visibleImport = ref(false)

const downloadUrl = `${import.meta.env.VITE_APP_BASE_API}v1/plan/sales-forecast/download-import-tpl`
const onImport = async () => {
  visibleImport.value = true
}
const batchOptions = [
  { label: "批量设置Asin", value: "asin", permission: [] },
  { label: "批量设置运输类型", value: "transportation", permission: [] },
  { label: "批量设置活跃状态", value: "activity", permission: [] },
  { label: "批量修改预测销量", value: "forecast", permission: [] },
]
const batchOptionsEvent = (e) => {
  let list = tableRef?.value.$table.getCheckboxRecords()
  if (!list.length && e != "forecast") {
    return ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
  }

  openConfirmInput(e, { id: list.map((v) => v.id) })
  // if (["lt_days", "stocking_status"].includes(e)) {
  //   openConfirmInput(e, { ids: list.map((v) => v.id) })
  // } else {
  //   EstimatedSalesRef.value.open(list.map((v) => v.id))
  // }
}

// 删除
const onDeleteManually = (row = null) => {
  let arr = tableRef?.value.$table.getCheckboxRecords()
  if (!arr.length) {
    return false
  }
  ElMessageBox.confirm(`此操作将删除 ${arr.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      deleteManually({ base_asin_id: arr.map((v) => v.id) }).then((res) => {
        query()
        ElMessage({ type: "success", message: "操作成功" })
      })
    } catch (e) {
      throw Error(e)
    }
  })
}

// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const onExport = () => {
  let rows = tableRef?.value.$table.getCheckboxRecords()
  let formData = initForm(tableRef?.value?.getQueryForm())
  let condition = {}
  if (rows?.length) {
    condition.id = rows.map((v) => v.id)
    condition.month = formData.month
  } else {
    condition = formData
  }
  DerivedCenterRef.value.open({
    tag_name: "SALES_FORECAST",
    condition,
  })
}
const callbackFn = (params) => {
  salesForecastCreateExportRecord(params).then((res) => {
    ElMessage.success(res.message)
  })
}

const showDaySales = () => {
  const { month } = tableRef?.value.getQueryForm()
  let tableData = tableRef?.value?.$table?.getData()
  let params = {
    month: {
      start: `${month?.[0]?.split("-")[0] - 1}-${month?.[0]?.split("-")[1]}`,
      end: `${month?.[1]?.split("-")[0] - 1}-${month?.[1]?.split("-")[1]}`,
    },
    id: tableData?.map((v) => v.id),
  }
  salesForecastListByDate(params).then((res) => {
    console.time()
    let data = {}
    let monthData = res.data?.[0].plan_sales_forecast?.map((v) => v.month)
    let monthKey = {}
    res.data.forEach((item) => {
      let obj = {}
      item.plan_sales_forecast.forEach((items) => {
        obj[items.month] = items
        let key = `${Number(items.month?.split("-")[0]) + 1}-${items.month?.split("-")[1]}`
        monthKey[key] = items.month
      })
      data[item.id] = obj
    })

    monthKey = Object.entries(monthKey)
    tableData.forEach((item) => {
      monthKey.forEach(([key, key1]) => {
        item[key].day_month = data?.[item.id]?.[key1].month
        item[key].day_total_sales = data?.[item.id]?.[key1].total_sales
      })
    })

    tableRef?.value?.$table?.updateData(tableData)
    console.timeEnd()
  })
}

const salesChange = (row) => {
  // console.log(row)
  let params = {
    id: row.id,
    sales: [
      {
        month: row.month,
        daily_sales: row.daily_sales,
        activity_sales: row.activity_sales,
      },
    ],
  }
  salesForecastBatchUpdateSales(params).then(async (res) => {
    ElMessage.success(res.message)
    query()
  })
}
import { assignAsin, transportationType, activityStatus, historyList, batchUpdateSalesForecast } from "./api.js"
const tableRef = ref()

const data = reactive({
  batchVisible: false,
  currentConfirm: {},
})
const { batchVisible, currentConfirm } = toRefs(data)

const handleConfirmSubmit = (param) => {
  let requests = null
  let params = {}
  switch (currentConfirm.value.type) {
    // 批量修改销量
    case "batchSales":
      params = {
        id: currentConfirm.value.row.id,
        sales: [],
      }
      params.sales = currentConfirm.value.row.plan_sales_forecast.map((v) => ({ month: v.month, ...param }))
      requests = salesForecastBatchUpdateSales
      break
    // 批量设置Asin
    case "asin":
      requests = assignAsin
      params = param
      break
    // 批量设置运输类型
    case "transportation":
      requests = transportationType
      params = param
      break
    // 批量设置活跃状态
    case "activity":
      requests = activityStatus
      params = param
      break
    // 批量修改预测销量
    case "forecast":
      requests = batchUpdateSalesForecast
      params = { ...param }

      params.sales_forecasts = params.sales_forecasts.replace(/\t/g, " ").split("\n")
      break

    default:
      break
  }
  if (currentConfirm.value.type == "forecast") {
    requests(params).then((res) => {
      if (res.data.length) {
        currentConfirm.value.form = {
          start_month: param.start_month,
          sales_forecasts: res.data?.join("\n"),
        }
      } else {
        query()
        batchVisible.value = false
        currentConfirm.value = {}
      }
    })
  } else {
    requests(params).then((res) => {
      ElMessage.success(res.message)
      query()
    })
    batchVisible.value = false
    currentConfirm.value = {}
  }
}

//

const openConfirmInput = (type, row) => {
  let confirmOpt = {}
  switch (type) {
    // 批量修改销量
    case "batchSales":
      confirmOpt = currentConfirmOpt.batchSales
      // confirmOpt.type = type
      confirmOpt.row = row
      break

    // 批量设置Asin
    case "asin":
      confirmOpt = currentConfirmOpt.asin
      confirmOpt.form.id = row.id
      confirmOpt.originOption = originOption.value
      break

    // 批量设置运输类型
    case "transportation":
      confirmOpt = currentConfirmOpt.transportation
      confirmOpt.form.id = row.id
      confirmOpt.originOption = originOption.value
      break

    // 批量设置活跃状态
    case "activity":
      confirmOpt = currentConfirmOpt.activity
      confirmOpt.form.id = row.id
      confirmOpt.originOption = originOption.value
      break

    // 批量修改预测销量
    case "forecast":
      confirmOpt = currentConfirmOpt.forecast
      break

    default:
      break
  }

  confirmOpt.type = type
  // console.log(confirmOpt)
  currentConfirm.value = confirmOpt
  batchVisible.value = true
}

const currentConfirmOpt = {
  batchSales: {
    // 批量修改销量
    title: "批量修改销量",
    fieldOptions: [
      {
        field: "daily_sales",
        label: "日常销量",
        style: { width: "300px" },
      },
      {
        field: "activity_sales",
        label: "活动销量",
        style: { width: "300px" },
      },
    ],
    rules: {},
  },
  asin: {
    // 批量修改Asin
    title: "批量修改Asin",
    form: {},
    fieldOptions: [{ label: "Asin", field: "asin", placeholder: "Asin", style: { width: "320px" } }],
    rules: { asin: [{ required: true, message: "请输入Asin", trigger: "blur" }] },
  },
  transportation: {
    // 批量修改运输类型
    title: "批量修改运输类型",
    form: {},
    fieldOptions: [
      {
        label: "运输类型",
        field: "transportation_type",
        type: "select",
        originField: "Base.BaseAsinList.TransportationTypeEnum",
        options: { placeholder: "运输类型" },
        style: { width: "320px" },
      },
    ],
    rules: { transportation_type: [{ required: true, message: "请选择", trigger: "change" }] },
  },
  activity: {
    // 批量修改活跃状态
    title: "批量修改活跃状态",
    form: {},
    fieldOptions: [
      {
        label: "活跃状态",
        field: "activity_status",
        type: "select",
        originField: "Base.BaseAsinList.ActivityStatusEnum",
        options: { placeholder: "活跃状态" },
        style: { width: "320px" },
      },
    ],
    rules: { activity_status: [{ required: true, message: "请选择", trigger: "change" }] },
  },

  forecast: {
    // 批量修改预测销量
    title: "批量修改预测销量",
    width: 1200,
    form: { sales_forecasts: "" },
    fieldOptions: [
      {
        field: "start_month",
        label: "修改月份",
        type: "dateTimeRangeNorm",
        itemProps: { type: "month", format: "YYYY-MM", valueFormat: "YYYY-MM", shortcuts: [], clearable: false },
      },
      {
        slot: "SalesForecasts",
        // field: "sales_forecasts",
        label: "预测销量",
        // placeholder: `国家 Asin sku 操作运营 X月日常 X月日常
        // 示例：
        // US B0CSDBB4N2 7395682 KoalaLuo 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
        // UK B0DPQ5KTJ6 9838734 KathyZhong 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0`,
        // type: "textarea",
        // autosize: { minRows: 4, maxRows: 6 },
      },
    ],
  },
}

// 查询
const query = () => {
  tableRef?.value.query()
}

const formShow = ref(false)
//获取下拉数据
onMounted(async () => {
  salesForecastDownloadImportYpl()
  getOption()

  setTimeout(() => {
    formShow.value = true
  }, 200)
})
// 初始化月份条件
import { parseTime } from "@/utils/ruoyi"
const getMonth = () => {
  let end = new Date()
  end.setTime(end.getTime() + 3600 * 1000 * 24 * 120)
  let month = [new Date(new Date().setHours(23, 59, 59, 0)), new Date(end.setHours(0, 0, 0, 0))].map((v) => parseTime(v, "{y}-{m}"))
  return month
}
// 枚举 数据
const originOption = ref({})
// import { getCountry } from "@/api"
import { getEnum, getAloneEnum } from "@/utils/enumUtils"
import { getAllSupplie } from "@/api"
// 获取下拉数据
const getOption = async () => {
  let keys = [
    "Base.BaseAsinList.TransportationTypeEnum",
    "Base.BaseAsinList.ActivityStatusEnum",
    "Base.BaseAsinList.IsFirstOrderEnum",
    "Base.BaseAsinList.IsNeedChangeEnum",
    "Base.BaseAsinList.ActivityStatusEnum",
  ]
  const data = await getEnum(keys)
  keys.forEach((key) => {
    originOption.value[key] = data[key]
  })
  originOption.value.amazonSite = (await getAloneEnum(["amazonSite"])).amazonSite

  const shopRes = await getShopOptions({ platform_ids: [2] })
  originOption.value.shopOpt = shopRes.data.map((n) => ({
    label: n.shop_name,
    value: n.shop_id,
  }))

  let allSupplie = (await getAllSupplie()).data
  originOption.value.supplier = allSupplie
  originOption.value.supplierCode = allSupplie?.filter((v) => v.supplier_coding)
}

const formOption = ref({ inline: true })
import {
  fieldList, // 搜索条件 配置
} from "./config.jsx"

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      skuRange: { type: "sku", value: "" },
      month: getMonth(),
    },
  },
  rowConfig: { height: 154 },
  showOverflow: false,
  columns: [],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          ...initForm(form),
          page: page.pageNum,
          page_size: page.pageSize,
        }
        return queryList(params)
      },
    },
  },
})
const initForm = (form) => {
  form.month = {
    start: form.month?.[0],
    end: form.month?.[1],
  }

  let keys = ["sku", "custom_sku", "asin", "supplier_code"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
    form[key] = form[key]?.map((v) => v.trim())
  })
  return form
}
const queryList = async (params) => {
  let res = null
  if (archived_at.value) {
    params.archived_at = archived_at.value
    // return historyList(params)
    res = await historyList(params)
  } else {
    res = await salesForecastList(params)
  }

  // let res = await salesForecastList(params)
  let monthColumns = res.data?.[0].plan_sales_forecast?.map((v) => ({
    ...monthColumn,
    title: v.month,
  }))
  let date = new Date()

  date = new Date(`${date.getFullYear()}-${date.getMonth() + 1}-01`).getTime()
  res.data.forEach((item) => {
    item.plan_sales_forecast.forEach((items) => {
      // 销量完成进度
      items.scale = ((Number(items.actual_sales / items.total_sales) || 0) * 100).toFixed(2)
      if (items.total_sales == 0) items.scale = 0
      items.disabled = new Date(`${items.month}-01`).getTime() < date
      item[items.month] = items
    })
  })
  tableOptins.columns = [...tableColumn, ...monthColumns, handleColumn]
  tableRef?.value?.$table.loadColumn(tableOptins.columns)
  setTimeout(() => {
    // 渲染
    tableRef?.value?.updateScroll()
  }, 100)
  // console.log(res.data)
  return res
}
const monthColumn = {
  title: "",
  width: 220,
  slots: {
    default: "monthColumn",
  },
}
// 操作列
const handleColumn = {
  title: "操作",
  width: 130,
  fixed: "right",
  slots: {
    default: ({ row }) => {
      return [
        <div>
          {/* <el-button link type="primary" onClick={() => openConfirmInput("batchSales", row)}>
            批量修改
          </el-button> */}
          <el-button link type="primary" onClick={() => logRef?.value.open({ id: row.id })}>
            日志
          </el-button>
        </div>,
      ]
    },
  },
}

const activityColor = {
  新品: "text-green",
  重点: "text-red",
}
const salesTagColor = {
  呆滞: "base-tag-warning",
  清库: "base-tag-danger",
  停售: "base-tag-info",
  default: "base-tag-primary",
}
// 固定列
const tableColumn = [
  { type: "checkbox", fixed: "left", width: 60 },
  {
    title: "图片",
    width: 120,
    slots: {
      default: ({ row }) => <el-image style="width:80px;height:80px" src={row.sku_attr_img} />,
    },
  },
  {
    title: "产品信息",
    width: 220,
    slots: {
      default: ({ row }) => (
        <div>
          <div class="flex items-center">
            <span class=" base-tag-success">{row.is_first_order_text}</span>
            <span class="base-tag-danger ml-[4px]">{row.is_need_change_text}</span>
          </div>

          <div class="flex items-center">
            <div class="flex mr-[4px]">
              <div class={`mr-[2px] ${salesTagColor[row.sales_status_text] || salesTagColor.default}`}>{row.sales_status_text}</div>
              <div class={` ${row.supply_status_text == "正常" ? "base-tag-success" : "base-tag-info-plain "}`}>{row.supply_status_text}</div>
            </div>
            <div class="text-blue">
              <VText title="SKU" value={row.sku} line={1} />
            </div>
          </div>

          <VText title="ASIN" value={row.asin} line={1} />
          <VText title="店铺" value={row.store_name} line={1} />

          <VText title="数据来源" value={row.add_method_text} line={1} />
          <VText title="供应商" value={row?.plan_asin_purchases?.supplier_code || row?.plan_asin_purchases?.supplier_id} line={1} />
          <div class="grid grid-cols-2">
            <VText title="国家" value={row.site_code} line={1} />
            <VText title="活跃度" value={row.activity_status_text} line={1} class={activityColor[row.activity_status_text] || ""} />
          </div>
        </div>
      ),
    },
  },
  {
    title: "产品名称",
    width: 240,
    slots: {
      default: ({ row }) => <VText value={row.sku_title} line={3} />,
    },
  },
  {
    title: "运输类型/天数",
    width: 120,
    slots: {
      default: ({ row }) => (
        <div>
          {row?.transportation_type_text || "-"}/{row.transportation_timeframe}天
        </div>
      ),
    },
  },
  {
    title: "销量信息",
    width: 180,
    slots: {
      default: ({ row }) => (
        <div class="grid grid-cols-2">
          <VText title="7天" value={row.asin_sales?.sales_num_seven_days} line={1} />
          <VText title="14天" value={row.asin_sales?.sales_num_fourteen_days} line={1} />
          <VText title="30天" value={row.asin_sales?.sales_num_thirty_days} line={1} />
          <VText title="90天" value={row.asin_sales?.sales_num_ninety_days} line={1} />

          <svg-icon icon-class="tubiao" class="text-[#3487ff] text-[1.5em]" onClick={() => AsinSalesTrendRef.value.open(row.id)} />
        </div>
      ),
    },
  },
  {
    title: "预估日均销量",
    width: 110,
    slots: {
      default: ({ row }) => (
        <div>
          <VText title="系统" value={row?.system_average_daily_sales} line={1} type="link" />
          <VText title="运营" value={row?.operation_average_daily_sales} line={1} type="link" />
        </div>
      ),
    },
  },
  {
    title: "人员信息",
    width: 200,
    slots: {
      default: ({ row }) => (
        <div>
          <VText title="计划" value={row.planner_user_text} line={1} />
          <VText title="采购" value={row.purchaser_user_text} line={1} />
          <VText title="运营" value={row.operator_user_text} line={1} />
          <VText title="部门" value={row.department_name} line={2} />
        </div>
      ),
    },
  },
]
</script>
<style lang="scss" scoped></style>
